import { decryptAes, encryptAes } from './encrypt';
interface ConfigType {
    type: 'localStorage' | 'sessionStorage',
    prefix: string,
    expire: number,
    isEncrypt: boolean
}

const config: ConfigType = {
    type: 'localStorage', //存储类型，localStorage | sessionStorage
    prefix: 'hars-admin', //key前缀
    expire: 24 * 60, //过期时间，默认为一天，单位为分钟
    isEncrypt: true, //支持加密、解密数据处理
};

const setStorage = (key: string, value: any | boolean, expire = 24 * 60) => {
    //设定值
    if (value === '' || value === null || value === undefined) {
        //空值重置
        value = null;
    }

    if (isNaN(expire) || expire < 0) {
        //过期时间值合理性判断
        throw new Error('Expire must be a number');
    }
    const data = {
        value: JSON.stringify(value), //存储值
        time: Date.now(), //存储日期
        expire: Date.now() + 1000 * 60 * expire, //过期时间
    };
    //是否需要加密，判断装载加密数据或原数据
    window[config.type].setItem(
        getStorageKey(key),
        config.isEncrypt ? encryptAes(JSON.stringify(data)) : JSON.stringify(data),
    );
    return true;
};

const getStorage = (key: string) => {
    key = getStorageKey(key);
    const item = window[config.type].getItem(key);
    if (!item) {
        return null;
    }
    const storageVal = config.isEncrypt ? JSON.parse(decryptAes(item)) : JSON.parse(item);
    const now = Date.now();
    if (now >= storageVal.expire) {
        //过期销毁
        removeStorage(key);
        return null;
        //不过期回值
    } else {
        return JSON.parse(storageVal.value);
    }
};
const getAllStorage = () => {
    //获取所有值
    const list: { [key: string]: any } = {};
    const keys = Object.keys(window[config.type]);
    keys.forEach((key) => {
        const value = getStorage(autoRemovePreFix(key));
        if (value !== null) {
            //如果值没有过期，加入到列表中
            list[autoRemovePreFix(key)] = value;
        }
    });
    return list;
};

const removeStorage = (key: string) => {
    //删除值
    if (config.prefix) {
        key = getStorageKey(key);
    }
    window[config.type].removeItem(key);
};
const clearStorage = () => {
    window[config.type].clear();
};
const getStorageKey = (key: string) => {
    if (!config.prefix) {
        return key
    }
    return `${config.prefix}_${key}`;
};
const autoRemovePreFix = (key: string) => {
    //删除前缀，进行增删改查
    const lineIndex = config.prefix.length + 1;
    return key.substr(lineIndex);
};

export {
    setStorage,
    getStorage,
    getAllStorage,
    removeStorage,
    clearStorage,
};
